package com.example.memoplus.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.memoplus.App;
import com.example.memoplus.R;
import com.example.memoplus.data.Memo;
import com.example.memoplus.data.MemoRepository;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "MainActivity";
    // 用于列表视图的数据
    private List<Memo> data;
    // 用于列表视图的适配器
    private MemoAdapter memoAdapter;
    // 列表视图
    private ListView listView;
    // MemoRepository
    private MemoRepository memoRepository;
    // 四个ImageButton
    private ImageButton ibAddMemo;
    private ImageButton ibUnFinshed;
    private ImageButton ibFinshed;
    private ImageButton ibMemoList;
    private LinearLayout ibMemoMenu;
    private Drawable checkedBg;     // 按钮选中时背景
    private Drawable unCheckedBg;   // 未选中时背景

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化成员变量
        listView = findViewById(R.id.lv_memo);
        ibMemoMenu = findViewById(R.id.ib_menu);
        ibAddMemo = findViewById(R.id.ib_add);
        ibUnFinshed = findViewById(R.id.ib_unfinshed);
        ibFinshed = findViewById(R.id.ib_finshed);
        ibMemoList = findViewById(R.id.ib_list);
        checkedBg = ContextCompat.getDrawable(this, R.drawable.ib_checked);
        unCheckedBg = ContextCompat.getDrawable(this, R.drawable.ib_unchecked);
        memoAdapter = new MemoAdapter();
        data = MemoRepository.getAllMemos();

        // 指定适配器
        listView.setAdapter(memoAdapter);
        // 监听
        ibAddMemo.setOnClickListener(this);
        ibUnFinshed.setOnClickListener(this);
        ibFinshed.setOnClickListener(this);
        ibMemoList.setOnClickListener(this);

        // 注册上下文菜单，与之相关联的主要重写有：onCreateContextMenu、onContextItemSelected
        registerForContextMenu(listView);
        Log.d(TAG, "onCreate: MainActivity");
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        // 检查触发上下文菜单的View是否是ListView
        if (v.getId() == R.id.lv_memo) {
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

            // 获取在ListView中长按的项的位置
            int position = info.position;

            // 根据需要在菜单中添加项
            menu.add(Menu.NONE, 1, Menu.NONE, "修改");
            menu.add(Menu.NONE, 2, Menu.NONE, "删除");
        }
    }
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;

        switch (item.getItemId()) {
            case 1:                     // 修改内容
                Intent intent = new Intent(this, EditMemoActivity.class);
                intent.putExtra("memo", data.get(position));
                startActivity(intent);
                break;
            case 2:                     // 删除内容
                MemoRepository.delMemoById(data.get(position).getId());
                data.remove(position);
                memoAdapter.notifyDataSetChanged();
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        memoRepository = new MemoRepository();
        if (v.getId() == R.id.ib_add) {                 // 添加memo
            startActivity(new Intent(this, EditMemoActivity.class));
        } else if (v.getId() == R.id.ib_list) {        // 显示全部的memo
            data.clear();
            data = MemoRepository.getAllMemos();
            memoAdapter.notifyDataSetChanged();
            changeButtonState(ibMemoList);
        } else if (v.getId() == R.id.ib_finshed) {     // 显示已完成的memo
            data.clear();
            data = MemoRepository.getFinshedMemos();
            memoAdapter.notifyDataSetChanged();
            changeButtonState(ibFinshed);
        } else if (v.getId() == R.id.ib_unfinshed) {  // 显示未完成的memo
            data.clear();
            data = MemoRepository.getUnFinshedMemos();
            memoAdapter.notifyDataSetChanged();
            changeButtonState(ibUnFinshed);
        }
    }




    @Override
    protected void onResume() {
        super.onResume();
        data.clear();
        data = getStateData();
        memoAdapter.notifyDataSetChanged();     // 更新视图显示内容
    }


    // 自定义适配器
    class MemoAdapter extends BaseAdapter {
        private static final String TAG = "MemoAdapter";
        @Override
        public int getCount() {
            return data.size();
        }
        @Override
        public Object getItem(int position) {
            return data.get(position);
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // 如果 convertView 是 null 的话，从缓存中获取
            if (convertView == null) {
                convertView = View.inflate(MainActivity.this, R.layout.item_memo, null);
            }
            // 获取当前数据对象
            Memo memo = data.get(position);
            // 监听button
            TextView textViewSummary = (TextView) convertView.findViewById(R.id.tv_memo_summary);
            TextView textViewTime = (TextView) convertView.findViewById(R.id.tv_memo_time);
            ImageView imageViewMarking = (ImageView) convertView.findViewById(R.id.iv_marking);
            textViewSummary.setText(memo.getContent());
            textViewTime.setText(memo.getCreationTime().toString());
            imageViewMarking.setImageResource(memo.isCompleted() == true ? R.drawable.iv_marked : R.drawable.iv_unmarked);
            Log.d("Debug1", "Memo completed status: " + memo.getId() + " 测试 " + memo.isCompleted());

            // 标记是否完成
            imageViewMarking.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    memo.setCompleted(memo.isCompleted() == true ? false : true);
                    MemoRepository.updateMemoById(memo);
                    ImageButton ib = getButtonState();
                    data.clear();
                    data = getStateData();
                    memoAdapter.notifyDataSetChanged();
                    Log.d(TAG, "onClick: imageView 被监听捕捉");
                }
            });
            return convertView;
        }
    }

    // 获取对应Button状态的数据
    public List<Memo> getStateData() {
        ImageButton buttonState = getButtonState();
        if (buttonState == ibFinshed) {
            return MemoRepository.getFinshedMemos();
        } else if (buttonState == ibUnFinshed) {
            return MemoRepository.getUnFinshedMemos();
        }
        return MemoRepository.getAllMemos();
    }

    // 获取按钮状态
    public ImageButton getButtonState() {
        ArrayList<ImageButton> imageButtons = new ArrayList<>();
        imageButtons.add(ibFinshed);
        imageButtons.add(ibUnFinshed);
        imageButtons.add(ibMemoList);
        for (ImageButton ib :
                imageButtons) {
            Log.d(TAG, "getButtonState: 1: " + ib.getBackground().getConstantState() + " 2: " + ContextCompat.getDrawable(App.getInstance(), R.drawable.ib_checked).getConstantState());
            if (ib.getBackground().getConstantState() == checkedBg.getConstantState()) {
                return ib;
            }
        }
        return null;
    }

    // 改变按钮状态
    public void changeButtonState(ImageButton imageButton) {
        ArrayList<ImageButton> imageButtons = new ArrayList<>();
        imageButtons.add(ibFinshed);
        imageButtons.add(ibUnFinshed);
        imageButtons.add(ibMemoList);
        imageButton.setBackground(checkedBg);
        imageButtons.remove(imageButton);
        for (ImageButton ib : imageButtons) {
            ib.setBackground(unCheckedBg);
        }
    }
}